package org.idol.generator.codegen.service.method;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.dom.java.*;

import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * @author coco
 * @date 2020-06-22 11:05
 **/
public class QueryByIdGenerator extends AbstractJavaInterfaceMethodGenerator{


    @Override
    public void addInterfaceElements(Interface interfaze) {
        Method method = new Method(introspectedTable.getQueryByIdType());
        method.setVisibility(JavaVisibility.PUBLIC);
        method.setAbstract(true);

        FullyQualifiedJavaType returnType = FullyQualifiedJavaType.getOptionalInstance();
        FullyQualifiedJavaType typeArgument = introspectedTable.getRules()
                .calculateAllFieldsClass();
        returnType.addTypeArgument(typeArgument);
        method.setReturnType(returnType);
        Set<FullyQualifiedJavaType> importedTypes = new TreeSet<>();
        importedTypes.add(returnType);
        importedTypes.add(typeArgument);

        if (introspectedTable.getRules().generatePrimaryKeyClass()) {
            FullyQualifiedJavaType type = new FullyQualifiedJavaType(
                    introspectedTable.getPrimaryKeyType());
            importedTypes.add(type);
            method.addParameter(new Parameter(type, "key")); //$NON-NLS-1$
        } else {
            // no primary key class - fields are in the base class
            // if more than one PK field, then we need to annotate the
            // parameters
            // for MyBatis3
            List<IntrospectedColumn> introspectedColumns = introspectedTable
                    .getPrimaryKeyColumns();
            for (IntrospectedColumn introspectedColumn : introspectedColumns) {
                FullyQualifiedJavaType type = introspectedColumn
                        .getFullyQualifiedJavaType();
                importedTypes.add(type);
                Parameter parameter = new Parameter(type, introspectedColumn
                        .getJavaProperty());
                method.addParameter(parameter);
            }
        }
        context.getCommentGenerator().addGeneralMethodComment(method,
                introspectedTable);
        interfaze.addImportedTypes(importedTypes);
        interfaze.addMethod(method);
    }
}
